package com.haiwei.poi.word.poi;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;

import java.util.List;

/**
 * XWPFTableRow 操作类.
 *
 * @date: 2022-06-26
 * @version: 1.0
 * @author: karry@haiwei.com
 */
public class HaiweiXWPFTableRowUtil {
    
    /**
     * 复制行
     * @param target
     * @param source
     * @param index
     */
    public static void copyTableRow(XWPFTableRow target, XWPFTableRow source) {
        // 复制样式
        if (source.getCtRow() != null) {
            target.getCtRow().setTrPr(source.getCtRow().getTrPr());
        }
        // 复制单元格
        for (int i = 0; i < source.getTableCells().size(); i++) {
            XWPFTableCell cell1 = target.getCell(i);
            XWPFTableCell cell2 = source.getCell(i);
            if (cell1 == null) {
                cell1 = target.addNewTableCell();
            }
            copyTableCell(cell1, cell2);
        }
    }
    
    /**
     * 复制单元格
     * @param target
     * @param source
     * @param index
     */
    public static void copyTableCell(XWPFTableCell target, XWPFTableCell source) {
        // 列属性
        if (source.getCTTc() != null) {
            target.getCTTc().setTcPr(source.getCTTc().getTcPr());
        }
        // 删除段落
        for (int pos = 0; pos < target.getParagraphs().size(); pos++) {
            target.removeParagraph(pos);
        }
        // 添加段落
        for (XWPFParagraph sourceP : source.getParagraphs()) {
            XWPFParagraph targetP = target.addParagraph();
            copyParagraph(targetP, sourceP);
        }
        
        // 添加嵌套的表格 现在还有问题，不能复制表格中 嵌套的表格
        /*for(XWPFTable sourceTable :  source.getTables()){
            final CTTbl sourceTableCctTbl1 = sourceTable.getCTTbl();
            target.getCTTc().insertNewTbl(0).set(sourceTableCctTbl1.copy());
        }*/
    
    }
    
    /**
     * 复制段落
     * @param target
     * @param source
     * @param index
     */
    public static void copyParagraph(XWPFParagraph target, XWPFParagraph source) {
        
        // 设置段落样式
        target.getCTP().setPPr(source.getCTP().getPPr());
        for (int pos = target.getRuns().size() - 1; pos >= 0; pos--) {
            target.removeRun(pos);
        }
        // copy 新的run
        for (XWPFRun sourceRun : source.getRuns()) {
            XWPFRun targetrun = target.createRun();
            copyRun(targetrun, sourceRun);
        }
        
    }
    
    /**
     * 复制Run
     * @param target
     * @param source
     * @param index
     */
    public static void copyRun( XWPFRun target, XWPFRun source) {
        // 设置run属性
        target.getCTR().setRPr(source.getCTR().getRPr());
        // 设置文本
        target.setText(source.text());
    }
    
}
